/**
 * 
 */
package com.udistrital.udcajbweb.comun.web.bean;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.ejb.EJBException;
import javax.faces.application.FacesMessage;
import javax.faces.component.ContextCallback;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.udistrital.framework.adminMenu.modelo.Amusr;
import com.udistrital.framework.excepcion.AplicacionExcepcion;
import com.udistrital.framework.excepcion.SistemaExcepcion;
import com.udistrital.framework.util.ParametrosSistema;
import com.udistrital.framework.util.ParametrosSistema.BaseNames;


/**
 * @author ccadavid
 * 
 */
public class BaseBean implements Serializable {

	private static final long serialVersionUID = -7743124116800078379L;
	
	private static final SimpleDateFormat FORMATO_FECHA_HORA = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	private static final SimpleDateFormat FORMATO_FECHA = new SimpleDateFormat("yyyy-MM-dd");
	private UIComponent component = null;
	private String objectName;
	private String ObjectDateSystem;
	private String HourDateSystem;
	
	
	public BaseBean() {
	}

	/**
	 * Adicionar al contexto un mensaje de error y obtenerlo de un archivo de propiedades
	 */
	public void addGeneralMensajeError() {
		String mensaje = ParametrosSistema.obtenerValorPropidedad(
				BaseNames.messages_business, "general_app_error");
		FacesContext.getCurrentInstance().addMessage(null,
				new FacesMessage(FacesMessage.SEVERITY_ERROR, mensaje, null));
	}

	public void addMensajeError(Exception exception) {
		FacesContext.getCurrentInstance().addMessage(
				null,
				new FacesMessage(FacesMessage.SEVERITY_ERROR, exception
						.getMessage(), exception.toString()));
	}

	public void addMensajeError(String mensaje) {
		FacesContext.getCurrentInstance().addMessage(null,
				new FacesMessage(FacesMessage.SEVERITY_ERROR, mensaje, null));
	}

	public void addMensajeError(String idComponente, String mensaje) {
		FacesContext.getCurrentInstance().addMessage(idComponente,
				new FacesMessage(FacesMessage.SEVERITY_ERROR, mensaje, null));
	}

	public void addMensajeInfo(String mensaje) {
		FacesContext.getCurrentInstance().addMessage(null,
				new FacesMessage(FacesMessage.SEVERITY_INFO, mensaje, mensaje));
	}

	public void addMensajeInfo(String idComponente, String mensaje) {
		FacesContext.getCurrentInstance().addMessage(idComponente,
				new FacesMessage(FacesMessage.SEVERITY_INFO, mensaje, null));
	}

	public void addMensajeWarn(String mensaje) {
		FacesContext.getCurrentInstance().addMessage(null,
				new FacesMessage(FacesMessage.SEVERITY_WARN, mensaje, null));
	}

	public void addMensajeWarn(String idComponente, String mensaje) {
		FacesContext.getCurrentInstance().addMessage(idComponente,
				new FacesMessage(FacesMessage.SEVERITY_WARN, mensaje, null));
	}

	public SelectItem getSelectItemPorValue(Object value, List<SelectItem> items) {
		SelectItem item = null;
		for (SelectItem selectItem : items) {
			if (value.equals(selectItem.getValue())) {
				item = selectItem;
				break;
			}
		}
		return item;
	}

	public String getLabelSelectItemPorValue(Object value,
			List<SelectItem> items) {
		SelectItem item = null;
		for (SelectItem selectItem : items) {
			if (value.equals(selectItem.getValue())) {
				item = selectItem;
				break;
			}
		}
		return item.getLabel();
	}

	public String getDescripcionSelectItemPorValue(Object value,
			List<SelectItem> items) {
		SelectItem item = null;
		for (SelectItem selectItem : items) {
			if ((Long) value == Long.parseLong(selectItem.getDescription())) {
				item = selectItem;
				break;
			}
		}
		return item.getLabel();
	}

	public void resetearUIInput(String[] idsUiInput) {
		UIViewRoot viewRoot = FacesContext.getCurrentInstance().getViewRoot();
		UIComponent comp = null;
		for (int i = 0; i < idsUiInput.length; i++) {
			comp = viewRoot.findComponent(idsUiInput[i]);
			if (comp != null && comp instanceof UIInput)
				((UIInput) comp).resetValue();
		}
	}

	public void removerBeanKeepAlive(String bean) {
		UIViewRoot viewRoot = FacesContext.getCurrentInstance().getViewRoot();
		Map<String, Object> atributos = viewRoot.getAttributes();
		atributos.remove("org.ajax4jsf.viewbean:" + bean);
	}

	public void removerAtributoDeUIViewRoot(String atributo) {
		UIViewRoot viewRoot = FacesContext.getCurrentInstance().getViewRoot();
		Map<String, Object> atributos = viewRoot.getAttributes();
		atributos.remove(atributo);
	}

	public String getInitParameter(String parameterName) {
		return FacesContext.getCurrentInstance().getExternalContext()
				.getInitParameter(parameterName);
	}

	public Map<String, String> getRequestParameterMap() {
		return FacesContext.getCurrentInstance().getExternalContext()
				.getRequestParameterMap();
	}

	public Map<String, Object> getRequestMap() {
		return FacesContext.getCurrentInstance().getExternalContext()
				.getRequestMap();
	}

	public Map<String, Object> getSessionMap() {
		return FacesContext.getCurrentInstance().getExternalContext()
				.getSessionMap();
	}

	public Map<String, Object> getApplicationMap() {
		return FacesContext.getCurrentInstance().getExternalContext()
				.getApplicationMap();
	}

	public Object getRequestAttribute(String attributeName) {
		Map<String, Object> map = getRequestMap();
		return map.get(attributeName);
	}

	public void setRequestAttribute(String attributeName, Object attributeValue) {
		Map<String, Object> map = getRequestMap();
		;
		map.put(attributeName, attributeValue);
	}

	public Object getSessionAttribute(String attributeName) {
		Map<String, Object> map = getSessionMap();
		return map.get(attributeName);
	}

	public void setSessionAttribute(String attributeName, Object attributeValue) {
		Map<String, Object> map = getSessionMap();
		map.put(attributeName, attributeValue);
	}

	public void removeSessionAttribute(String attributeName) {
		Map<String, Object> map = getSessionMap();
		map.remove(attributeName);
	}

	public String getRequestParameter(String parameterName) {
		return getRequestParameterMap().get(parameterName);
	}

	public Amusr getUsuarioSesion() {
		Amusr amusr = (Amusr) getSessionAttribute("usuario");
		return amusr;
	}

	public String getDirectorioTrabajo() {
		return ((ServletContext) FacesContext.getCurrentInstance()
				.getExternalContext().getContext()).getRealPath("/");
	}

	public String getContextName() {
		return ((ServletContext) FacesContext.getCurrentInstance()
				.getExternalContext().getContext()).getServletContextName();
	}

	public UIComponent findComponent(String clientId) {
		FacesContext context = FacesContext.getCurrentInstance();
		context.getViewRoot().invokeOnComponent(context, clientId,
				new ContextCallback() {

					public void invokeContextCallback(FacesContext arg0,
							UIComponent arg1) {
						component = arg1;
					}
				});
		return component;
	}

	public void downloadFile(InputStream pInputStream, String pFileName)
			throws IOException {
		int contentLength = pInputStream.available();

		// Init servlet response.
		FacesContext context = FacesContext.getCurrentInstance();
		HttpServletResponse response = getHttpServletResponse();
		response.setContentType("application/x-download; charset=ISO-8859-1");
		// response.setContentType("application/vnd.ms-excel");
		response.setContentLength(contentLength);
		// response.setHeader("Content-Disposition","inline; filename=\"" +
		// pFileName + "\"");
		response.setHeader("Content-disposition", "attachment; filename=\""
				+ pFileName + "\"");
		OutputStream out = response.getOutputStream();
		// Write file contents to response.
		int valor = 0;
		// pInputStream.reset();
		while ((valor = pInputStream.read()) != -1) {
			out.write(valor);
		}
		out.flush();
		// Finalize task.
		pInputStream.close();
		context.responseComplete();
	}

	public HttpSession getHttpSession() {
		return (HttpSession) FacesContext.getCurrentInstance()
				.getExternalContext().getSession(false);
	}

	public HttpServletRequest getHttpServletRequest() {
		return (HttpServletRequest) FacesContext.getCurrentInstance()
				.getExternalContext().getRequest();
	}

	public HttpServletResponse getHttpServletResponse() {
		return (HttpServletResponse) FacesContext.getCurrentInstance()
				.getExternalContext().getResponse();
	}

	protected void mostrarExcepcion(Throwable e) {
		if (e instanceof EJBException) {
			e = e.getCause() != null ? e.getCause() : e;
		}

		if (e instanceof AplicacionExcepcion) {
			addMensajeError(e.getMessage());
		} else if (e instanceof SistemaExcepcion) {
			addMensajeError(e.getMessage());
			e.printStackTrace();
		} else {
			addGeneralMensajeError();
			e.printStackTrace();
		}
	}
	
	protected String formatearFechaHora(Date fecha){
		return fecha != null ? FORMATO_FECHA_HORA.format(fecha) : null;
	}
	
	protected String formatearFecha(Date fecha){
		return fecha != null ? FORMATO_FECHA.format(fecha) : null;
	}

	/**
	 * @return the objectName
	 */
	public String getObjectName() {
		return objectName;
	}

	/**
	 * @param objectName the objectName to set
	 */
	public void setObjectName(String objectName) {
		this.objectName = objectName;
	}

	/**
	 * @return the objectDateSystem
	 */
	public String getObjectDateSystem() {
		return ObjectDateSystem;
	}

	/**
	 * @param objectDateSystem the objectDateSystem to set
	 */
	public void setObjectDateSystem(String objectDateSystem) {
		ObjectDateSystem = objectDateSystem;
	}

	/**
	 * @return the hourDateSystem
	 */
	public String getHourDateSystem() {
		return HourDateSystem;
	}

	/**
	 * @param hourDateSystem the hourDateSystem to set
	 */
	public void setHourDateSystem(String hourDateSystem) {
		HourDateSystem = hourDateSystem;
	}

	
	
}
